//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package zmee.sso;

import com.alibaba.fastjson.JSON;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.util.HttpClientUtils;
import kd.bos.workflow.engine.msg.AbstractMessageServiceHandler;
import kd.bos.workflow.engine.msg.ctx.MessageContext;
import kd.bos.workflow.engine.msg.info.MessageInfo;
import kd.bos.workflow.engine.msg.info.ToDoInfo;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Title   二开消息渠道解析类：泛微
 * Depict
 * Remark
 * Date    2023-06-28
 * Author  fenny
 * Version 1.0
 * PRD     统⼀审批中⼼接⼝调⽤.pdf
 */
public class YSWeaverMessageServiceHandler extends AbstractMessageServiceHandler {

    private static final Log logger = LogFactory.getLog(YSWeaverMessageServiceHandler.class);

    /**
     * 写入【OA统一待办日志】
     */
    private static void writeLog(MessageContext messageContext, String messagetype, String flowid, String billnumber, String nodename, String message, String request, String response, String creator, String receiver, String posturl, boolean issuccess) {
        // OA统一待办日志
        DynamicObject bill = BusinessDataServiceHelper.newDynamicObject("zmee_log_oapush");
        // 从编码规则获取单据编码
        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(bill.getDataEntityType().getName(), bill, null);
        // 设置【编码】
        bill.set("number", CodeRuleServiceHelper.getNumber(codeRule, bill));
        // 设置【名称】
        bill.set("name", messagetype);
        // 设置【消息类型】
        bill.set("zmee_messagetype", messagetype);
        // 设置【流程实例id】
        bill.set("zmee_flowid", flowid);
        // 设置【单据编号】
        bill.set("zmee_billnumber", billnumber);
        // 设置【单据类型】
        bill.set("zmee_billtype", messageContext.getEntityNumber());
        // 设置【节点名称】
        bill.set("zmee_nodename", nodename);
        // 设置【消息类型】
        bill.set("zmee_message", message);
        // 设置【请求】
        bill.set("zmee_request", request);
        // 设置【response】
        bill.set("zmee_response", response);
        // 设置【数据状态】
        bill.set("status", "C");
        // 设置【使用状态】
        bill.set("enable", "1");
        // 设置【创建人】
        bill.set("creator", creator);
        // 设置【创建日期】
        bill.set("zmee_createdate", new Date());
        // 设置【接收人】
        bill.set("zmee_receiver", receiver);
        // 设置【接收日期】
        bill.set("zmee_receiverdate", new Date());
        // 设置【请求地址】
        bill.set("zmee_posturl", posturl);
        // 设置【是否成功】
        bill.set("zmee_issuccess", issuccess);
        // 保存单据
        SaveServiceHelper.save(new DynamicObject[]{bill});
    }

    /**
     * 写入【OA统一待办日志】
     */
    private static void writeLogByMessage(MessageInfo message, String messagetype, String flowid, String billnumber, String nodename, String returnMessage, String request, String response, String creator, String receiver, String posturl, boolean issuccess) {
        // OA统一待办日志
        DynamicObject bill = BusinessDataServiceHelper.newDynamicObject("zmee_log_oapush");
        // 从编码规则获取单据编码
        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(bill.getDataEntityType().getName(), bill, null);
        // 设置【编码】
        bill.set("number", CodeRuleServiceHelper.getNumber(codeRule, bill));
        // 设置【名称】
        bill.set("name", messagetype);
        // 设置【消息类型】
        bill.set("zmee_messagetype", messagetype);
        // 设置【流程实例id】
        bill.set("zmee_flowid", flowid);
        // 设置【单据编号】
        bill.set("zmee_billnumber", billnumber);
        // 设置【单据类型】
        bill.set("zmee_billtype", message.getEntityNumber());
        // 设置【节点名称】
        bill.set("zmee_nodename", nodename);
        // 设置【消息类型】
        bill.set("zmee_message", returnMessage);
        // 设置【请求】
        bill.set("zmee_request", request);
        // 设置【response】
        bill.set("zmee_response", response);
        // 设置【数据状态】
        bill.set("status", "C");
        // 设置【使用状态】
        bill.set("enable", "1");
        // 设置【创建人】
        bill.set("creator", creator);
        // 设置【创建日期】
        bill.set("zmee_createdate", new Date());
        // 设置【接收人】
        bill.set("zmee_receiver", receiver);
        // 设置【接收日期】
        bill.set("zmee_receiverdate", new Date());
        // 设置【请求地址】
        bill.set("zmee_posturl", posturl);
        // 设置【是否成功】
        bill.set("zmee_issuccess", issuccess);
        // 保存单据
        SaveServiceHelper.save(new DynamicObject[]{bill});
    }

    @Override
    public void sendMessage(MessageContext ctx, MessageInfo message) {
        // 单据主键ID
        String businessKey = ctx.getBusinessKey();
        // 单据标识
        String entityNumber = ctx.getEntityNumber();

        logger.info("businessKey：{},entityNumber:{}", businessKey, entityNumber);

        // 获取单据完整对象
        DynamicObject billDy = BusinessDataServiceHelper.loadSingle(businessKey, entityNumber);

        // 构建接口调用参数
        JSONObject requestJson = new JSONObject();
        String requestJsonStr = "";
        String returnResultStr = "";
        String operResult = "";
        String returnMessage = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = "";
        // 获取消息渠道待办接口地址
        DynamicObject dynobj = BusinessDataServiceHelper.loadSingle(getConfig().getId(), "msg_channel", "zmee_createtodo");

        // 流程实例ID
        String flowid = message.getId().toString();
        // String flowid = "FNA"+ctx.getProcessInstanceId();
        logger.info("flowid:" + flowid);
        // 代办人员用户名集合
        List<Long> userIds = message.getUserIds();
        List<String> userNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", userIds);
        String receivers = userNames.toString().replace("[", "").replace("]", "").replace(" ", "");
        //增加对jinxiaodie的过滤，如果是jinxiaodie则不发送消息
        if (StringUtils.equals(receivers, "jinxiaodie")) {
            return;
        }
        // 待办发起人集合
        List<Long> startUserIds = new ArrayList<>();
        startUserIds.add(message.getUserIds().get(0));
        String creatorIds = startUserIds.get(0).toString();
        // 发起人用户名
        List<String> creatorNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", startUserIds);
        String creators = creatorNames.get(0).replace("[", "").replace("]", "");
        // 发起人姓名
        List<String> Names = YSCommonUtil.getSelectColumByIds("bos_user", "name", startUserIds);
        String Name = Names.get(0).replace("[", "").replace("]", "");
        if (dynobj != null) {
            url = dynobj.getString("zmee_createtodo");
        }

        // 如果消息渠道对应的url为空
        if (StringUtils.isEmpty(url)) {
            writeLogByMessage(message, "sendMessage", flowid, "", "消息", "泛微消息渠道的待办接口地址未维护，请检查维护！（路径：系统管理-消息平台-消息渠道）", "", "", "1", receivers, "", false);
            sendErrorMessage("消息ID：" + flowid + "，推送泛微消息失败！！，原因：" + "泛微消息渠道的待办接口地址未维护，请检查并维护！（路径：系统管理-消息平台-消息渠道）", startUserIds, Name, startUserIds.get(0), message.getEntityNumber(), message.getId());
            return;
        }

        try {
            // 异构系统标识
            requestJson.put("syscode", "hn_opc");
            // 流程实例id
            requestJson.put("flowid", flowid);
            // 流程标题
            String requestname = message.getTitle();
            // 流程类型名称
            if ("src_bidopen".equals(entityNumber)) {
                // 如果单据标识是【开标准备】取表头的：项目名称
                requestname = billDy.getString("bidname");
            }
            // 流程标题
            requestJson.put("requestname", requestname);
            // 流程类型名称（加）
            requestJson.put("workflowname", "优采云待办");
            // 接收⼈所属节点（加）（否）
            // requestJson.put("receivernodename", "优采云待办");
            // 自定义
            requestJson.put("YSWeaverMessageServiceHandler", "优采云待办");
            // 节点名称
            requestJson.put("nodename", "消息");

            // PC端地址（否）

            // 匹配www.域名开头的正则
            String pcUrl = message.getContentUrl();
            pcUrl = pcUrl.replaceAll("(http|https)://(www.)?(\\w+(\\.)?)+", "");
            // 匹配ip的正则
            pcUrl = pcUrl.replace("http://", "").replace("https://", "");
            pcUrl = pcUrl.replaceAll("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)", "");

            requestJson.put("pcurl", pcUrl + "&flowid=" + flowid);
            logger.info("sendmessage url:" + pcUrl);
            // APP端地址（否）
            // String appurl_g = message.getContentUrl().replace("https://opc.zmeeol.com", "");
            requestJson.put("appurl", pcUrl + "&device=mob");

            // 创建人
            requestJson.put("creator", creators);
            // 创建时间
            String createdatetime = simpleDateFormat.format(message.getSendTime());
            requestJson.put("createdatetime", createdatetime);
            // 接收人账号
            requestJson.put("receiver", receivers);
            // 接收⼈类型（加） 0：分配号 1：⼈员标识号 2：登录账号
            requestJson.put("receiver_type", "2");
            // 接收时间
            requestJson.put("receivedatetime", createdatetime);

            // 流程处理状态 0：待办 2：已办 4：办结 8：抄送（待阅） -1：删除
            requestJson.put("isremark", "8");
            // 流程查看状态  0：未读
            requestJson.put("viewtype", "1");

            // 时间戳字段
            requestJson.put("receivets", String.valueOf(System.currentTimeMillis()));
            // 应⽤系统流程主键（加）
            requestJson.put("workflowcode", "hn_opc" + flowid);
            // ⾃定义字段（否）
            // requestJson.put("custom", "custom");

            logger.info("抄送：requestJson:" + requestJson);

            logger.info("sendMessage调用接口的url：" + url + "\nsendMessage调用接口的参数：\n" + requestJson);

            // 调用泛微接口
            String returnResult = this.postData2ofs(url, requestJson.toString());
            if (returnResult == null || StringUtils.equals("", returnResult)) {
                logger.info("代码到这里了>>>>>");
                //tryAgainByMessage(message,"sendMessage",flowid,"","消息",startUserIds,Name,creatorIds,receivers,requestJson,url);
                return;
            }

            requestJsonStr = requestJson.toString();

            // 结果转成JSONObject
            JSONObject returnResultObj = JSONObject.fromObject(returnResult);

            returnResultStr = returnResult;

            logger.info("sendMessage调用接口的返回值：" + returnResult);

            if(returnResultObj.containsKey("data")) {
                // 从result中获取data
                JSONObject dataObject = returnResultObj.getJSONObject("data");

                logger.info("dataObject: \n" + dataObject);

                // 操作结果
                operResult = dataObject.getString("operResult");
                // 接⼝执⾏结果描述
                returnMessage = dataObject.getString("message");
            }
        } catch (Exception var7) {
            //tryAgainByMessage(message,"sendMessage",flowid,"","消息",startUserIds,Name,creatorIds,receivers,requestJson,url);
        } finally {
            if (StringUtils.equals(operResult, "1")) {
                writeLogByMessage(message, "sendMessage", flowid, "", "消息", returnMessage, requestJsonStr, returnResultStr, creatorIds, receivers, url, true);
            } else if (StringUtils.equals(operResult, "0")) {
                writeLogByMessage(message, "sendMessage", flowid, "", "消息", returnMessage, requestJsonStr, returnResultStr, creatorIds, receivers, url, false);
                sendErrorMessage("消息ID：" + flowid + "，推送泛微消息失败！！，原因：" + returnMessage, startUserIds, Name, startUserIds.get(0), message.getEntityNumber(), message.getId());
            }
        }
    }

    @Override
    public void createToDo(MessageContext messageContext, ToDoInfo toDoInfo) {
        JSONObject requestJson = new JSONObject();
        String requestJsonStr = "";
        String returnResultStr = "";
        String operResult = "";
        String message = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = "";
        // 从【消息渠道】获取【待办接口地址】
        DynamicObject dynobj = BusinessDataServiceHelper.loadSingle(this.getConfig().getId(), "msg_channel", "zmee_createtodo");
        String flowid = "hn_opc" + messageContext.getProcessInstanceId();
        logger.info("createToDo：flowid:" + flowid);
        List<String> businessKeys = new ArrayList<>();
        businessKeys.add(String.valueOf(messageContext.getBusinessKey()));
        logger.info("获取节点名称" + YSCommonUtil.getNodeColumnByBusinessKeys("wf_task", "name", businessKeys));
        String nodenameStr = YSCommonUtil.getNodeColumnByBusinessKeys("wf_task", "name", businessKeys).toString();
        nodenameStr = nodenameStr.replace("[", "").replace("]", "");
        String billNumber = YSCommonUtil.getNodeColumnByBusinessKeys("wf_task", "billno", businessKeys).toString();
        billNumber = billNumber.replace("[", "").replace("]", "");
        List<Long> userIds = toDoInfo.getUserIds();
        List<String> userNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", userIds);
        String receivers = userNames.toString().replace("[", "").replace("]", "").replace(" ", "");
        // 如果发送人不是jinxiaodie
        if (!StringUtils.equals(receivers, "jinxiaodie")) {
            List<Long> startUserIds = new ArrayList<>();
            startUserIds.add(messageContext.getStartUserId());
            String creatorIds = startUserIds.get(0).toString();
            List<String> creatorNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", startUserIds);
            String creators = creatorNames.get(0).replace("[", "").replace("]", "");
            List<String> Names = YSCommonUtil.getSelectColumByIds("bos_user", "name", startUserIds);
            String Name = Names.get(0).replace("[", "").replace("]", "");
            if (dynobj != null) {
                url = dynobj.getString("zmee_createtodo");
            }

            if (StringUtils.isEmpty(url)) {
                writeLog(messageContext, "createToDo", flowid, billNumber, nodenameStr, "泛微消息渠道的待办接口地址未维护，请检查维护！（路径：系统管理-消息平台-消息渠道）", "", "", "1", receivers, "", false);
                this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：泛微消息渠道的待办接口地址未维护，请检查并维护！（路径：系统管理-消息平台-消息渠道）", startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
            } else {
                try {
                    // 异构系统标识
                    requestJson.put("syscode", "hn_opc");
                    // 流程实例id
                    requestJson.put("flowid", flowid);
                    // 流程标题
                    String requestname = toDoInfo.getTitle();
                    if (billNumber != null) {
                        QFilter qFilter;
                        DynamicObject gxcwf;
                        String department;
                        DynamicObject zjmi_department;
                        String istrue;
                        String pricetaxtotal;
                        int i;
                        String pNumber;
                        if (billNumber.contains("GXFKS")) {
                            qFilter = new QFilter("billno", "=", billNumber);
                            gxcwf = BusinessDataServiceHelper.loadSingle("ap_payapply", "zjmi_department,applycause,applyamount,paycurrency", new QFilter[]{qFilter});
                            if (gxcwf != null) {
                                department = "";
                                zjmi_department = gxcwf.getDynamicObject("wycy_department");
                                if (zjmi_department != null) {
                                    department = zjmi_department.getString("name");
                                }

                                istrue = gxcwf.getString("applycause");
                                pricetaxtotal = gxcwf.getString("applyamount");
                                i = pricetaxtotal.indexOf(".");
                                pNumber = pricetaxtotal.substring(0, i + 3);
                                DynamicObject paycurrency = gxcwf.getDynamicObject("paycurrency");
                                String number = paycurrency.getString("number");
                                requestJson.put("requestname", department + "-" + Name + "-" + istrue + "-" + number + pNumber + "");
                                logger.info("createToDo:requestJson:" + requestJson);
                            } else {
                                requestJson.put("requestname", requestname + "，单据编号：" + billNumber + "");
                            }
                        } else if (billNumber.contains("GXCWF")) {
                            qFilter = new QFilter("billno", "=", billNumber);
                            gxcwf = BusinessDataServiceHelper.loadSingle("ap_finapbill", "department,zjmi_checkboxfield,billtypeid,zjmi_applycause,pricetaxtotal,zjmi_payamountsum,currency", new QFilter[]{qFilter});
                            if (gxcwf != null) {
                                department = "";
                                zjmi_department = gxcwf.getDynamicObject("department");
                                if (zjmi_department != null) {
                                    department = zjmi_department.getString("name");
                                }

                                istrue = gxcwf.getString("zjmi_checkboxfield");
                                logger.info("createToDo:istrue" + istrue);
                                pricetaxtotal = gxcwf.getString("pricetaxtotal");
                                i = pricetaxtotal.indexOf(".");
                                pNumber = pricetaxtotal.substring(0, i + 3);
                                logger.info("createToDo:pNumber" + pNumber);
                                String zjmi_payamountsum = gxcwf.getString("zjmi_payamountsum");
                                int index = zjmi_payamountsum.indexOf(".");
                                String intNumber = zjmi_payamountsum.substring(0, index + 3);
                                logger.info("createToDo:intNumber" + intNumber);
                                DynamicObject billtypeid = gxcwf.getDynamicObject("billtypeid");
                                String name = billtypeid.getString("name");
                                logger.info("createToDo:name" + name);
                                String applycause = gxcwf.getString("zjmi_applycause");
                                logger.info("createToDo:zjmi_applycause" + applycause);
                                DynamicObject paycurrency = gxcwf.getDynamicObject("currency");
                                String number = paycurrency.getString("number");
                                if ("true".equals(istrue)) {
                                    requestJson.put("requestname", department + "-" + Name + "-" + applycause + "-" + number + intNumber + "");
                                    logger.info("createToDo:requestJson:" + requestJson);
                                } else if ("false".equals(istrue)) {
                                    requestJson.put("requestname", department + "-" + Name + "-" + name + "-" + number + pNumber + "");
                                    logger.info("createToDo:requestJson:" + requestJson);
                                }
                            } else {
                                requestJson.put("requestname", requestname + "，单据编号：" + billNumber + "");
                            }
                        } else {
                            requestJson.put("requestname", requestname + "，单据编号：" + billNumber + "");
                        }
                    } else {
                        requestJson.put("requestname", requestname + "，单据编号：" + billNumber + "");
                    }
                    // 流程类型名称（加）
                    requestJson.put("workflowname", "优采云待办");
                    // 接收⼈所属节点（加）（否）
                    // requestJson.put("receivernodename", "优采云待办");
                    // 节点名称
                    requestJson.put("nodename", nodenameStr);

                    // PC端地址（否）

                    // 匹配www.域名开头的正则
                    String pcUrl = toDoInfo.getUrl();
                    pcUrl = pcUrl.replaceAll("(http|https)://(www.)?(\\w+(\\.)?)+", "");
                    // 匹配ip的正则
                    pcUrl = pcUrl.replace("http://", "").replace("https://", "");
                    pcUrl = pcUrl.replaceAll("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)", "");

                    requestJson.put("pcurl", pcUrl);
                    logger.info("YSWeaverMessageServiceHandler记录移动端地址" + pcUrl + "&device=mob");
                    // APP端地址（否）
                    // String appurl_g = toDoInfo.getUrl().replace("https://opc.zmeeol.com", "");
                    requestJson.put("appurl", pcUrl + "&device=mob");

                    //requestJson.put("appurl", toDoInfo.getUrl() + "&device=mob");

                    // 创建人
                    requestJson.put("creator", creators);
                    // 创建时间
                    String createdatetime = simpleDateFormat.format(new Date());
                    requestJson.put("createdatetime", createdatetime);
                    // 接收人账号
                    requestJson.put("receiver", receivers);
                    // 接收⼈类型（加） 0：分配号 1：⼈员标识号 2：登录账号
                    requestJson.put("receiver_type", "2");
                    // 接收时间
                    requestJson.put("receivedatetime", createdatetime);

                    // 流程处理状态 0：待办 2：已办 4：办结 8：抄送（待阅） -1：删除
                    requestJson.put("isremark", "0");
                    // 流程查看状态  0：未读
                    requestJson.put("viewtype", "0");

                    // 时间戳字段
                    requestJson.put("receivets", String.valueOf(System.currentTimeMillis()));
                    // 应⽤系统流程主键（加）
                    requestJson.put("workflowcode", "hn_opc" + flowid);
                    // ⾃定义字段（否）
                    // requestJson.put("custom", "custom");

                    logger.info("createToDo调用接口的url：" + url + "\ncreateToDo调用接口的参数：\n" + requestJson);

                    // 调用接口
                    String returnResult = this.postData2ofs(url, requestJson.toString());
                    if (returnResult != null && !StringUtils.equals("", returnResult)) {

                        logger.info("createToDo调用接口的返回值：" + returnResult);

                        requestJsonStr = requestJson.toString();

                        // 结果转成JSONObject
                        JSONObject returnResultObj = JSONObject.fromObject(returnResult);

                        if (returnResultObj.containsKey("data")) {
                            // 从result中获取data
                            JSONObject dataObject = returnResultObj.getJSONObject("data");

                            logger.info("dataObject: \n" + dataObject);

                            // 赋值操作
                            returnResultStr = returnResult;
                            // 赋值结果码 1：成功 0：失败
                            operResult = dataObject.getString("operResult");
                            // 接口返回信息
                            message = dataObject.getString("message");
                        }
                        return;
                    }

                    logger.info("代码到这里了>>>>>");

                    this.tryAgain(messageContext, "createToDo", flowid, billNumber, nodenameStr, startUserIds, Name, creatorIds, receivers, requestJson, url);
                } catch (Exception var44) {
                    logger.info("代码到这里了>>>>>");
                    this.tryAgain(messageContext, "createToDo", flowid, billNumber, nodenameStr, startUserIds, Name, creatorIds, receivers, requestJson, url);
                    return;
                } finally {
                    logger.info("代码到这里了>>>>>");
                    if (StringUtils.equals(operResult, "1")) {
                        writeLog(messageContext, "createToDo", flowid, billNumber, nodenameStr, message, requestJsonStr, returnResultStr, creatorIds, receivers, url, true);
                    } else if (StringUtils.equals(operResult, "0")) {
                        writeLog(messageContext, "createToDo", flowid, billNumber, nodenameStr, message, requestJsonStr, returnResultStr, creatorIds, receivers, url, false);
                        this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：" + message, startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
                    }
                }
            }
        }
    }

    @Override
    public void dealToDo(MessageContext messageContext, ToDoInfo toDoInfo) {
        JSONObject requestJson = new JSONObject();
        JSONObject oldrequestJson = new JSONObject();
        String requestJsonStr = "";
        String returnResultStr = "";
        String operResult = "";
        String message = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = "";
        DynamicObject dynobj = BusinessDataServiceHelper.loadSingle(this.getConfig().getId(), "msg_channel", "zmee_dealtodo");
        String oldflowid = String.valueOf(toDoInfo.getTaskId());
        String flowid = "hn_opc" + messageContext.getProcessInstanceId();
        logger.info("dealToDo：flowid:" + flowid);
        List<String> businessKeys = new ArrayList();
        businessKeys.add(String.valueOf(messageContext.getBusinessKey()));
        String nodenameStr = YSCommonUtil.getNodeColumnByBusinessKeys("wf_task", "name", businessKeys).toString();
        nodenameStr = nodenameStr.replace("[", "").replace("]", "");
        String billNumber = YSCommonUtil.getNodeColumnByBusinessKeys("wf_task", "billno", businessKeys).toString();
        billNumber = billNumber.replace("[", "").replace("]", "");
        List<Long> userIds = toDoInfo.getUserIds();
        List<String> userNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", userIds);
        String receivers = userNames.toString().replace("[", "").replace("]", "").replace(" ", "");
        if (!StringUtils.equals(receivers, "jinxiaodie")) {
            List<Long> startUserIds = new ArrayList();
            startUserIds.add(messageContext.getStartUserId());
            String creatorIds = startUserIds.get(0).toString();
            List<String> creatorNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", startUserIds);
            String creators = creatorNames.get(0).replace("[", "").replace("]", "");
            List<String> Names = YSCommonUtil.getSelectColumByIds("bos_user", "name", startUserIds);
            String Name = Names.get(0).replace("[", "").replace("]", "");
            if (dynobj != null) {
                url = dynobj.getString("zmee_dealtodo");
            }

            if (StringUtils.isEmpty(url)) {
                writeLog(messageContext, "dealToDo", flowid, billNumber, nodenameStr, "泛微消息渠道的已办接口地址未维护，请检查维护！（路径：系统管理-消息平台-消息渠道）", "", "", "1", receivers, "", false);
                this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：泛微消息渠道的已办接口地址未维护，请检查并维护！（路径：系统管理-消息平台-消息渠道）", startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
            } else {
                try {
                    // 异构系统标识
                    requestJson.put("syscode", "hn_opc");
                    oldrequestJson.put("syscode", "hn_opc");
                    // 流程实例id
                    requestJson.put("flowid", flowid);
                    oldrequestJson.put("flowid", oldflowid);
                    // 流程标题
                    String requestname = toDoInfo.getTitle();
                    if (billNumber != null) {
                        QFilter qFilter;
                        DynamicObject gxcwf;
                        String department;
                        DynamicObject zjmi_department;
                        String istrue;
                        String pricetaxtotal;
                        int i;
                        String pNumber;
                        if (billNumber.contains("GXFKS")) {
                            qFilter = new QFilter("billno", "=", billNumber);
                            gxcwf = BusinessDataServiceHelper.loadSingle("ap_payapply", "zjmi_department,applycause,applyamount,paycurrency", new QFilter[]{qFilter});
                            if (gxcwf != null) {
                                department = "";
                                zjmi_department = gxcwf.getDynamicObject("zjmi_department");
                                if (zjmi_department != null) {
                                    department = zjmi_department.getString("name");
                                }

                                istrue = gxcwf.getString("applycause");
                                pricetaxtotal = gxcwf.getString("applyamount");
                                i = pricetaxtotal.indexOf(".");
                                pNumber = pricetaxtotal.substring(0, i + 3);
                                DynamicObject paycurrency = gxcwf.getDynamicObject("paycurrency");
                                String number = paycurrency.getString("number");
                                requestJson.put("requestname", department + "-" + Name + "-" + istrue + "-" + number + pNumber + "");
                                logger.info("dealToDo:requestJson:" + requestJson);
                            } else {
                                requestJson.put("requestname", "请处理" + Name + "发起的单据，单据编号：" + billNumber + "");
                            }
                        } else if (billNumber.contains("GXCWF")) {
                            qFilter = new QFilter("billno", "=", billNumber);
                            gxcwf = BusinessDataServiceHelper.loadSingle("ap_finapbill", "department,zjmi_checkboxfield,billtypeid,zjmi_applycause,pricetaxtotal,zjmi_payamountsum,currency", new QFilter[]{qFilter});
                            if (gxcwf != null) {
                                department = "";
                                zjmi_department = gxcwf.getDynamicObject("department");
                                if (zjmi_department != null) {
                                    department = zjmi_department.getString("name");
                                }

                                logger.info("dealToDo:istrue" + zjmi_department);
                                istrue = gxcwf.getString("zjmi_checkboxfield");
                                logger.info("dealToDo:istrue" + istrue);
                                pricetaxtotal = gxcwf.getString("pricetaxtotal");
                                i = pricetaxtotal.indexOf(".");
                                pNumber = pricetaxtotal.substring(0, i + 3);
                                logger.info("dealToDo:pNumber" + pNumber);
                                String zjmi_payamountsum = gxcwf.getString("zjmi_payamountsum");
                                int index = zjmi_payamountsum.indexOf(".");
                                String intNumber = zjmi_payamountsum.substring(0, index + 3);
                                logger.info("dealToDo:intNumber" + intNumber);
                                DynamicObject billtypeid = gxcwf.getDynamicObject("billtypeid");
                                String name = billtypeid.getString("name");
                                logger.info("dealToDo:name" + name);
                                String applycause = gxcwf.getString("zjmi_applycause");
                                logger.info("dealToDo:zjmi_applycause" + applycause);
                                DynamicObject paycurrency = gxcwf.getDynamicObject("currency");
                                String number = paycurrency.getString("number");
                                if ("true".equals(istrue)) {
                                    requestJson.put("requestname", department + "-" + Name + "-" + applycause + "-" + number + intNumber + "");
                                    logger.info("dealToDo:requestJson:" + requestJson);
                                } else if ("false".equals(istrue)) {
                                    requestJson.put("requestname", department + "-" + Name + "-" + name + "-" + number + pNumber + "");
                                    logger.info("dealToDo:requestJson:" + requestJson);
                                }
                            } else {
                                requestJson.put("requestname", "请处理" + Name + "发起的单据，单据编号：" + billNumber + "");
                            }
                        } else {
                            requestJson.put("requestname", "请处理" + Name + "发起的单据，单据编号：" + billNumber + "");
                        }
                    } else {
                        requestJson.put("requestname", "请处理" + Name + "发起的单据，单据编号：" + billNumber + "");
                    }
                    // 流程类型名称（加）
                    requestJson.put("workflowname", "优采云待办");
                    oldrequestJson.put("workflowname", "优采云待办");
                    // 接收⼈所属节点（加）（否）
                    // requestJson.put("receivernodename", "优采云待办");
                    // 节点名称
                    requestJson.put("nodename", nodenameStr);
                    oldrequestJson.put("nodename", nodenameStr);

                    // PC端地址（否）

                    // 匹配www.域名开头的正则
                    String pcUrl = toDoInfo.getUrl();
                    pcUrl = pcUrl.replaceAll("(http|https)://(www.)?(\\w+(\\.)?)+", "");
                    // 匹配ip的正则
                    pcUrl = pcUrl.replace("http://", "").replace("https://", "");
                    pcUrl = pcUrl.replaceAll("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)", "");

                    requestJson.put("pcurl", pcUrl);
                    oldrequestJson.put("pcurl", pcUrl);
                    // APP端地址（否）
                    // String appurl_g = toDoInfo.getUrl().replace("https://opc.zmeeol.com", "");
                    requestJson.put("appurl", pcUrl + "&device=mob");
                    oldrequestJson.put("appurl", pcUrl + "&device=mob");

                    // 创建人
                    requestJson.put("creator", creators);
                    oldrequestJson.put("creator", creators);
                    // 创建时间
                    String createdatetime = simpleDateFormat.format(new Date());
                    requestJson.put("createdatetime", createdatetime);
                    oldrequestJson.put("createdatetime", createdatetime);
                    // 接收人账号
                    requestJson.put("receiver", receivers);
                    oldrequestJson.put("receiver", receivers);
                    // 接收⼈类型（加） 0：分配号 1：⼈员标识号 2：登录账号
                    requestJson.put("receiver_type", "2");
                    oldrequestJson.put("receiver_type", "2");
                    // 接收时间
                    requestJson.put("receivedatetime", createdatetime);
                    oldrequestJson.put("receivedatetime", createdatetime);

                    // 流程处理状态 0：待办 2：已办 4：办结 8：抄送（待阅） -1：删除
                    requestJson.put("isremark", "2");
                    oldrequestJson.put("isremark", "2");
                    // 流程查看状态  0：未读
                    requestJson.put("viewtype", "0");
                    oldrequestJson.put("viewtype", "0");

                    // 时间戳字段
                    requestJson.put("receivets", String.valueOf(System.currentTimeMillis()));
                    oldrequestJson.put("receivets", String.valueOf(System.currentTimeMillis()));
                    // 应⽤系统流程主键（加）
                    requestJson.put("workflowcode", "hn_opc" + flowid);
                    oldrequestJson.put("workflowcode", "hn_opc" + flowid);
                    // ⾃定义字段（否）
                    // requestJson.put("custom", "custom");
                    // oldrequestJson.put("custom", "custom");

                    logger.info("dealToDo调用接口的url：" + url + "\ndealToDo调用接口的参数requestJson：\n" + requestJson);
                    logger.info("dealToDo调用接口的url：" + url + "\ndealToDo调用接口的参数oldrequestJson：\n" + oldrequestJson);

                    // 调用接口
                    String returnResult = this.postData2ofs(url, requestJson.toString());

                    if (returnResult == null || StringUtils.equals("", returnResult)) {
                        logger.info("代码到这里了>>>>>");
                        this.tryAgain(messageContext, "dealToDo", flowid, billNumber, nodenameStr, startUserIds, Name, creatorIds, receivers, requestJson, url);
                        return;
                    }

                    logger.info("dealToDo调用接口的返回值：" + returnResult);

                    requestJsonStr = requestJson.toString();
                    JSONObject returnResultObj = JSONObject.fromObject(returnResult);
                    returnResultStr = returnResult;

                    if (returnResultObj.containsKey("data")) {
                        // 获取返回结果的data
                        JSONObject dataObject = returnResultObj.getJSONObject("data");

                        logger.info("dataObject: \n" + dataObject);

                        // 赋值操作
                        operResult = dataObject.getString("operResult");
                        // 接口返回信息
                        message = dataObject.getString("message");
                    }
                } catch (Exception var46) {
                    this.tryAgain(messageContext, "dealToDo", flowid, billNumber, nodenameStr, startUserIds, Name, creatorIds, receivers, requestJson, url);
                } finally {
                    if (StringUtils.equals(operResult, "1")) {
                        writeLog(messageContext, "dealToDo", flowid, billNumber, nodenameStr, message, requestJsonStr, returnResultStr, creatorIds, receivers, url, true);
                    } else if (StringUtils.equals(operResult, "0")) {
                        writeLog(messageContext, "dealToDo", flowid, billNumber, nodenameStr, message, requestJsonStr, returnResultStr, creatorIds, receivers, url, false);
                        this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：" + message, startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
                    }
                }
            }
        }
    }

    @Override
    public void deleteToDo(MessageContext messageContext, ToDoInfo toDoInfo) {
        JSONObject requestJson = new JSONObject();
        JSONObject oldrequestJson = new JSONObject();
        String requestJsonStr = "";
        String returnResultStr = "";
        String operResult = "";
        String message = "";
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = "";
        DynamicObject dynobj = BusinessDataServiceHelper.loadSingle(this.getConfig().getId(), "msg_channel", "zmee_deletetodo");
        String oldflowid = String.valueOf(toDoInfo.getTaskId());
        String flowid = "hn_opc" + messageContext.getProcessInstanceId();
        logger.info("deleteToDo：flowid:" + flowid);
        List<String> businessKeys = new ArrayList();
        businessKeys.add(String.valueOf(messageContext.getBusinessKey()));
        String billNumber = YSCommonUtil.getNodeColumnByBusinessKeys("wf_task", "billno", businessKeys).toString();
        billNumber = billNumber.replace("[", "").replace("]", "");
        List<Long> userIds = toDoInfo.getUserIds();
        List<String> userNames = YSCommonUtil.getSelectColumByIds("bos_user", "username", userIds);
        String receivers = userNames.toString().replace("[", "").replace("]", "").replace(" ", "");
        List<Long> startUserIds = new ArrayList();
        startUserIds.add(Long.parseLong("1"));
        if (dynobj != null) {
            url = dynobj.getString("zmee_deletetodo");
        }

        if (StringUtils.isEmpty(url)) {
            logger.info("代码到这里了>>>>>");
            writeLog(messageContext, "deleteToDo", flowid, "", "", "泛微消息渠道的删除待办接口地址未维护，请检查维护！（路径：系统管理-消息平台-消息渠道）", "", "", "1", receivers, "", false);
            this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：泛微消息渠道的删除待办接口地址未维护，请检查并维护！（路径：系统管理-消息平台-消息渠道）", startUserIds, "administrator", startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
        } else if (StringUtils.isEmpty(receivers)) {
            logger.info("代码到这里了>>>>>");
            writeLog(messageContext, "deleteToDo", flowid, "", "", "未获取到待办接收人数据！！，toDoInfo:" + toDoInfo, "", "", "1", receivers, "", true);
            this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，删除泛微待办失败！！，原因：未获取到待办接收人数据！！，toDoInfo:" + toDoInfo, startUserIds, "administrator", startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
        } else {
            String[] var20 = receivers.split(",");
            int var21 = var20.length;

            for (int var22 = 0; var22 < var21; ++var22) {
                String receiver = var20[var22];

                try {
                    if (StringUtils.equals(receiver, "jinxiaodie")) {
                        return;
                    }

                    requestJson.put("syscode", "hn_opc");
                    oldrequestJson.put("syscode", "hn_opc");
                    requestJson.put("flowid", flowid);
                    oldrequestJson.put("flowid", oldflowid);
                    requestJson.put("userid", receiver);
                    oldrequestJson.put("userid", receiver);

                    logger.info("deleteToDo调用接口的url：" + url + "\ndeleteToDo调用接口的参数：\n" + requestJson);
                    logger.info("deleteToDo调用接口的url：" + url + "\ndeleteToDo调用接口的参数：\n" + oldrequestJson);

                    String returnResult = this.postData2ofs(url, requestJson.toString());
                    if (returnResult != null && !StringUtils.equals("", returnResult)) {

                        logger.info("deleteToDo调用接口的返回值：" + returnResult);

                        requestJsonStr = requestJson.toString();

                        JSONObject resultObject = JSONObject.fromObject(returnResult);

                        if (resultObject.containsKey("data")) {

                            JSONObject dataObject = resultObject.getJSONObject("data");

                            logger.info("dataObject: \n" + dataObject);

                            if (dataObject.containsKey("operResult")) {

                                JSONObject returnResultObj = dataObject.getJSONObject("operResult");

                                if (returnResultObj != null) {
                                    returnResultStr = returnResult;
                                    operResult = returnResultObj.getString("operResult");
                                    message = returnResultObj.getString("message");
                                }
                            }
                        }
                        continue;
                    }

                    logger.info("代码到这里了>>>>>");

                    this.tryAgain(messageContext, "deleteToDo", flowid, "", "", startUserIds, "administrator", "1", receivers, requestJson, url);
                } catch (Exception var29) {
                    this.tryAgain(messageContext, "deleteToDo", flowid, "", "", startUserIds, "administrator", "1", receiver, requestJson, url);
                    continue;
                } finally {
                    if (StringUtils.equals(operResult, "1")) {
                        writeLog(messageContext, "deleteToDo", flowid, "", "", message, requestJsonStr, returnResultStr, "1", receiver, url, true);
                    } else if (StringUtils.equals(operResult, "0")) {
                        writeLog(messageContext, "deleteToDo", flowid, "", "", message, requestJsonStr, returnResultStr, "1", receiver, url, false);
                        this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，删除泛微待办失败！！，原因：" + message, startUserIds, "administrator", startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
                    }
                }
                return;
            }
        }
    }

    /**
     * Apache工具类【EntityUtils】POST格式调用接口
     * param json 请求数据
     * param url url地址
     * param token 访问令牌
     */
    public String sendPost(String url, Object json, String token) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json;charset=utf-8");
        if (token != null && !"".equals(token)) {
            post.addHeader("X-Access-Token", token);
        }
        String result = null;
        try {
            StringEntity s = new StringEntity(JSON.toJSONString(json), "utf-8");
            s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应返回
            result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");

            logger.info("YSWeaverMessageServiceHandler.sendPos打散组装前的响应：" + result);

            // 打散：将字符串按照原字符编码进行打散
            if (result != null && !"".equals(result)) {
                result = new String(result.getBytes("ISO8859-1"), "UTF-8");
            }
            // result = new String (result.getBytes("UTF-8"),"UTF-8");

            logger.info("YSWeaverMessageServiceHandler.sendPos打散组装后的响应：" + result);

        } catch (Exception e) {
            logger.error("YSWeaverMessageServiceHandler.sendPost, 发送 POST 请求出现异常！\n", e.getMessage());
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 苍穹工具类【HttpClientUtils】POST格式调用接口
     * param url url地址
     * param header 请求头数据
     * param body 请求体数据
     */
    public String postInfo2(String url, JSONObject header, JSONObject body, String accessToken) {
        // 初始化结果
        String result = null;

        // header为空时
        if (header == null || header.size() == 0) {
            header = new JSONObject();
        }

        // body为空时
        if (body == null || body.size() == 0) {
            body = new JSONObject();
        }

        // 必要参数
        header.put("Content-Type", "application/json; charset=UTF-8");

        // 如果传递的accessToken不为空
        if (accessToken != null && !"".equals(accessToken)) {
            header.put("access_token", accessToken);
        }

        // 初始化参数headerMap
        Map<String, String> headerMap = new HashMap<>();
        // 获取所有key
        Iterator it1 = header.keys();
        // 循环转换
        while (it1.hasNext()) {
            // map :: key
            String key = String.valueOf(it1.next());
            // map :: value
            Object value = header.get(key);
            // 不为空
            if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                headerMap.put(key, String.valueOf(value));
            }
        }

        // 初始化参数bodyMap
        Map<String, Object> bodyMap = new HashMap<>();
        // 获取所有key
        Iterator it2 = body.keys();
        // 循环转换
        while (it2.hasNext()) {
            // map :: key
            String key = String.valueOf(it2.next());
            // map :: value
            Object value = body.get(key);
            // 不为空
            if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                bodyMap.put(key, value);
            }
        }

        try {
            // 调用苍穹标准工具类接收返回参数
            result = HttpClientUtils.post(url, headerMap, bodyMap);

            logger.info("YSWeaverMessageServiceHandler.postInfo2 打散组装前的响应：" + result);

            // 打散：将字符串按照原字符编码进行打散
            if (result != null && !"".equals(result)) {
                result = new String(result.getBytes("ISO8859-1"), "UTF-8");
            }

            logger.info("YSWeaverMessageServiceHandler.postInfo2 打散组装后的响应：" + result);

        } catch (IOException e) {
            logger.error("YSWeaverMessageServiceHandler.postInfo2, 发送 POST 请求出现异常！\n", e.getMessage());
        }

        return result;
    }

    /**
     * 调用接口方法
     * param posturl url地址
     * param param 参数
     */
    public String postData2ofs(String posturl, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(posturl);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out.write(param);
            out.flush();

            String line;
            for (in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); (line = in.readLine()) != null; result = result + line) {
            }

            JSONObject object = JSONObject.fromObject(result);
            String returnResult = object.toString();
            String var11 = returnResult;
            return var11;
        } catch (Exception var21) {
            logger.error("zmee.cloud.bos.OAMessageServiceHandler,发送 POST请求出现异常！", var21.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var20) {
                var20.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 根据接口返回的信息写入【OA统一待办日志】
     */
    private void tryAgain(MessageContext messageContext, String messagetype, String flowid, String billNumber, String nodenameStr, List<Long> startUserIds, String Name, String creator, String receiver, JSONObject request, String url) {
        int count = 0;
        String returnResult = "";
        logger.info("代码到这里了 tryAgain 进入 >>>>>");
        while (true) {
            try {
                returnResult = this.postData2ofs(url, request.toString());
                if (returnResult == null) {
                    logger.info("代码到这里了 tryAgain ++count >>>>>");
                    ++count;
                } else {
                    logger.info("returnResult 返回结果: \n" + returnResult);
                }

                if (count >= 3) {
                    logger.info("代码到这里了 tryAgain count >= 3 >>>>>");
                    writeLog(messageContext, messagetype, flowid, billNumber, nodenameStr, "接口调用异常,响应为null", request.toString(), "null", creator, receiver, url, false);
                    this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：接口调用异常,响应为null,请联系系统管理员！", startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
                    break;
                }

                JSONObject returnResultObj = JSONObject.fromObject(returnResult);

                logger.info("data是否存在: " + returnResultObj.containsKey("data") + "\nreturnResultObj: \n" + returnResultObj);

                if (returnResultObj.containsKey("data")) {
                    JSONObject dataObject = returnResultObj.getJSONObject("data");
                    if (dataObject.containsKey("operResult")) {
                        if (StringUtils.equals("1", dataObject.getString("operResult"))) {
                            writeLog(messageContext, messagetype, flowid, billNumber, nodenameStr, dataObject.getString("message"), request.toString(), returnResult, creator, receiver, url, true);
                        } else {
                            writeLog(messageContext, messagetype, flowid, billNumber, nodenameStr, dataObject.getString("message"), request.toString(), returnResult, creator, receiver, url, false);
                            this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：" + dataObject.getString("message"), startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
                        }
                        break;
                    } else {
                        logger.info("代码到这里了 tryAgain operResult else >>>>>");
                        ++count;
                    }
                } else {
                    logger.info("代码到这里了 tryAgain data else >>>>>");
                    ++count;
                }
            } catch (Exception var17) {
                ++count;

                try {
                    logger.info("代码到这里了 tryAgain.sleep 开始 >>>>>");
                    long start1 = System.currentTimeMillis();

                    TimeUnit.MINUTES.sleep(1L);

                    long end1 = System.currentTimeMillis();
                    logger.info("代码到这里了 tryAgain.sleep 结束 >>>>> \n耗时: " + (end1 - start1));

                } catch (InterruptedException var16) {
                    ++count;
                    // var16.printStackTrace();
                    logger.info("代码到这里了 tryAgain 异常 InterruptedException >>>>> \n" + var16.getMessage());
                }

                if (count >= 3) {
                    logger.info("代码到这里了 tryAgain count >= 3 >>>>>");

                    writeLog(messageContext, messagetype, flowid, billNumber, nodenameStr, "接口调用异常" + var17.getMessage(), request.toString(), returnResult, creator, receiver, url, false);
                    this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：" + var17.getMessage(), startUserIds, Name, startUserIds.get(0), messageContext.getEntityNumber(), messageContext.getTaskId());
                    break;
                }
            }
        }
        logger.info("代码到这里了 tryAgain 结束 >>>>>");
    }

    private void tryAgainByMessage(MessageInfo message, String messagetype, String flowid, String billNumber, String nodenameStr, List<Long> startUserIds, String Name, String creator, String receiver, JSONObject request, String url) {
        int count = 0;
        String returnResult = "";
        logger.info("代码到这里了>>>>>");
        while (true) {
            try {
                returnResult = this.postData2ofs(url, request.toString());
                if (returnResult == null) {
                    ++count;
                }

                if (count >= 3) {
                    writeLogByMessage(message, "sendMessage", flowid, "", "消息", "接口调用异常,响应为null", request.toString(), "null", creator, receiver, url, false);
                    this.sendErrorMessage("消息ID：" + flowid + "，推送泛微待办失败！！，原因：接口调用异常,响应为null,请联系系统管理员！", startUserIds, Name, startUserIds.get(0), message.getEntityNumber(), message.getId());
                    break;
                }

                JSONObject returnResultObj = JSONObject.fromObject(returnResult);

                if (returnResultObj.containsKey("data")) {

                    JSONObject dataObject = returnResultObj.getJSONObject("data");

                    logger.info("dataObject: \n" + dataObject);

                    if(dataObject.containsKey("operResult")) {
                        if (StringUtils.equals("1", dataObject.getString("operResult"))) {
                            writeLogByMessage(message, "sendMessage", flowid, "", "消息", dataObject.getString("message"), request.toString(), returnResult, creator, receiver, url, true);
                        } else {
                            writeLogByMessage(message, "sendMessage", flowid, "", "消息", dataObject.getString("message"), request.toString(), returnResult, creator, receiver, url, false);
                            this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：" + dataObject.getString("message"), startUserIds, Name, startUserIds.get(0), message.getEntityNumber(), message.getId());
                        }
                    }
                    break;
                }
            } catch (Exception var17) {
                ++count;

                try {
                    TimeUnit.MINUTES.sleep(1L);
                } catch (InterruptedException var16) {
                    ++count;
                }

                if (count >= 3) {
                    writeLogByMessage(message, "sendMessage", flowid, "", "消息", "接口调用异常" + var17.getMessage(), request.toString(), returnResult, creator, receiver, url, false);
                    this.sendErrorMessage("单据：" + billNumber + "，流程实例ID：" + flowid + "，推送泛微待办失败！！，原因：" + var17.getMessage(), startUserIds, Name, startUserIds.get(0), message.getEntityNumber(), message.getId());
                    break;
                }
            }
        }
    }

    /**
     * 写入错误【OA统一待办日志】
     */
    private void sendErrorMessage(String title, List<Long> userIds, String senderName, Long senderId, String entityNumber, Long bizDataId) {
        MessageInfo message = new MessageInfo();
        message.setType("message");
        message.setTitle(title);
        message.setUserIds(userIds);
        message.setSenderName(senderName);
        message.setSenderId(senderId);
        message.setEntityNumber(entityNumber);
        message.setOperation("save");
        message.setBizDataId(bizDataId);
        message.setTag("重要，必读");
        message.setPubaccNumber("flowassist");
        message.setContent(title);

        try {
            Long var8 = MessageCenterServiceHelper.sendMessage(message);
        } catch (Exception var9) {
            var9.printStackTrace();
        }
    }

    private boolean checkOA(String flowid) {
        QFilter qFilter = new QFilter("processinstanceid", "=", flowid);
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("WF_HIPROCINST", "billno,entitynumber", new QFilter[]{qFilter});
        if (dynamicObject == null) {
            return false;
        } else {
            return "zjmi_ssc_taskbill".equals(dynamicObject.getString("entitynumber"));
        }
    }

    String postmessage(String context, String users, String username, String workflowId) {
        String message = "";
        String transfer = "<web:userid>" + users + "</web:userid>";
        String billno = "<web:fieldValue>" + context + "</web:fieldValue>";
        String userse = "<web:fieldValue>" + username + "</web:fieldValue>";
        String beforetransfer = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:fron=\"http://localhost/services/FrontWorkflowService\" xmlns:web=\"http://webservices.workflow.weaver\">\n   <soapenv:Header/>\n   <soapenv:Body>\n      <fron:doCreateXXTXWorkflowRequest>\n         <fron:in0>\n            <web:accountType>1</web:accountType>\n            <web:sourcefrom>每刻</web:sourcefrom>";
        String aftertransfer = "<web:workflowRequestInfo>\n               <web:requestName>" + context + "</web:requestName>\n               <web:workflowBaseInfo>\n                  <web:workflowId>" + workflowId + "</web:workflowId>\n               </web:workflowBaseInfo>\n               <web:workflowMainTableInfo>\n                  <web:requestRecords>\n                     <web:WorkflowRequestTableRecord>\n                        <web:workflowRequestTableFields>\n                           <web:WorkflowRequestTableField>\n                              <web:edit>true</web:edit>\n                              <web:fieldName>mdgurl</web:fieldName>";
        String afterbillno = "<web:view>true</web:view>\n                           </web:WorkflowRequestTableField>\n                           <web:WorkflowRequestTableField>\n                              <web:edit>true</web:edit>\n                              <web:fieldName>cs</web:fieldName>\n                              <web:fieldValue></web:fieldValue>\n                              <web:view>true</web:view>\n                           </web:WorkflowRequestTableField>\n\t\t\t\t\t\t   <web:WorkflowRequestTableField>\n                              <web:edit>true</web:edit>\n                              <web:fieldName>jsrzh</web:fieldName>";
        String afteruserse = "<web:view>true</web:view>\n                           </web:WorkflowRequestTableField>\n                        </web:workflowRequestTableFields>\n                     </web:WorkflowRequestTableRecord>\n                  </web:requestRecords>\n               </web:workflowMainTableInfo>\n            </web:workflowRequestInfo>\n         </fron:in0>\n      </fron:doCreateXXTXWorkflowRequest>\n   </soapenv:Body>\n</soapenv:Envelope>";
        message = beforetransfer + transfer + aftertransfer + billno + afterbillno + userse + afteruserse;
        return message;
    }

    String sendOA(String message, String url) throws Exception {
        String result = HttpRequestUtil.requestPost(message, url);
        return result;
    }
}
